package com.leisurexi.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.SocketChannel;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;

/**
 * Nio 阻塞式客户端
 *
 * @author: leisurexi
 * @date: 2021-01-05 22:52
 */
public class BlockClient {

    public static void main(String[] args) {
        try (
                // 1. 获取通道
                SocketChannel socketChannel = SocketChannel.open(new InetSocketAddress("localhost", 8888));
                // 2. 打开本地文件的 channel
                FileChannel fileChannel = FileChannel.open(Paths.get("C:\\Users\\lwx\\Desktop\\goddess\\goddess.jpg"), StandardOpenOption.READ)
        ) {
            // 3. 使用 buffer 作为数据载体
            ByteBuffer buffer = ByteBuffer.allocate(1024);
            // 4. 读取数据，发往服务端（这其实是将图片数据写入 buffer 的操作）
            while (fileChannel.read(buffer) != -1) {
                // 切换 buffer 为读模式
                buffer.flip();
                // 发送数据到服务端
                socketChannel.write(buffer);
                // 清空 buffer 准备下一次写入数据
                buffer.clear();
            }

            // 告知服务端数据已发送完毕
            socketChannel.shutdownOutput();

            // 接收服务端的恢复
            int len = 0;
            while ((len = socketChannel.read(buffer)) != -1) {
                buffer.flip();
                System.out.println(new String(buffer.array(), 0, len));
                buffer.clear();
            }

        } catch (IOException e) {
            e.printStackTrace();
        }

    }

}
